<template>
  <div class="content">
    <div class="pageSearchView">
      <SearchForm v-model="searchParam" :fields="searchFields" :handleSearch="handleSearch"/>
    </div>

    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">
          列表信息
          <el-icon>
            <house-icon/>
          </el-icon>
        </div>
        <div class="pageTableButView">
          <el-button :icon="Plus" @click="handleAdd">新建</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" height="calc(100vh - 350px)" :loading="isLoading">
        <el-table-column label="序号" align="center">
          <template #default="scope">
            {{ (paginationParams.current - 1) * paginationParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="周期名称" align="center"/>
        <el-table-column prop="code" label="周期编码" align="center">
          <template #default="scope">
            {{ scope.row.code }}
          </template>
        </el-table-column>
        <el-table-column prop="materialType" label="周期有效期" align="center" width="300">
          <template #default="scope">
            {{ scope.row.cycleStartDate + ' ~ ' + scope.row.cycleEndDate }}
          </template>
        </el-table-column>

        <!-- 动态列渲染 -->
        <el-table-column v-for="col in columns" :key="col.key" :prop="col.key" :label="col.label" align="center"/>
        <el-table-column label="操作" align="center" fixed="right" width="180">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)" size="small" plain text :icon="Edit">编辑</el-button>
            <el-button @click="handleDel(scope.row)" type="danger" size="small" plain text :icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="paginationParams.current"
                       v-model:page-size="paginationParams.pageSize" layout="total, sizes, prev, pager, next"
                       :total="pageTotal"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </div>
    <!-- 弹窗表单 -->
    <el-dialog v-model="showCrud" :title="crudTitle" width=600>
      <el-form :model="formData" label-width="130px" ref="ruleFormRef" :rules="rules">
        <el-row>
          <el-form-item label="周期名称" required prop="name">
            <el-input v-model="formData.name" placeholder="请输入周期名称" style="width: 400px"/>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="周期编码" required prop="code">
            <el-input v-model="formData.code" placeholder="请输入周期编码" style="width: 400px"/>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="周期有效期" required prop="cycleStartDate">
            <el-date-picker
                v-model="cycleDateRange"
                type="datetimerange"
                style="width:400px"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                @change="handleCycleDateChange"
            />
          </el-form-item>
        </el-row>

        <el-form-item label="周期类型" prop="triggerCycleType">
          <el-radio-group v-model="formData.triggerCycleType">
            <el-radio :value="1">日</el-radio>
            <el-radio :value="2">周</el-radio>
            <el-radio :value="3">月</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="周期间隔" prop="invokeFrequency" v-if="[1, 2, 3].includes(formData.triggerCycleType)">
          <el-input-number v-model="formData.invokeFrequency" :min="0" style="width: 400px"/>
        </el-form-item>
        <el-form-item label="提前生成天数" prop="advanceDate" v-if="[1, 2, 3].includes(formData.triggerCycleType)">
          <el-input-number v-model="formData.advanceDate" :min="0" style="width: 400px" @change="calculateTriggerTime"/>
        </el-form-item>
        <el-form-item label="执行开始周期" prop="invokeBegin" v-if="[2].includes(formData.triggerCycleType)">
          <el-select multiple v-model="formData.invokeBegin" placeholder="请选择周期" clearable style="width: 400px">
            <el-option v-for="(item, index) of week" :key="index" :label="item.value" :value="item.label"/>
          </el-select>
        </el-form-item>
        <el-form-item label="执行开始日期" prop="invokeBegin" v-if="[3].includes(formData.triggerCycleType)">
          <el-select multiple v-model="formData.invokeBegin" placeholder="请选择日期" clearable style="width: 400px">
            <el-option v-for="n in 31" :key="n" :label="`${n}号`" :value="n"/>
          </el-select>
        </el-form-item>
        <el-form-item label="执行开始时刻" prop="triggerTime" v-if="[1, 2, 3].includes(formData.triggerCycleType)">
          <div class="trigger-time-container">
            <el-date-picker
                v-model="triggerDateOnly"
                type="date"
                placeholder="选择日期"
                :disabled="true"
                format="YYYY-MM-DD"
                style="width: 180px; margin-right: 10px;"
            />
            <el-time-picker
                v-model="triggerTimeOnly"
                format="HH:mm:ss"
                value-format="HH:mm:ss"
                arrow-control
                placeholder="请选择时间"
                style="width: 210px"
                @change="updateFullTriggerTime"
            />
          </div>
<!--          <div class="trigger-time-hint">-->
<!--            提示：日期根据"周期有效期开始时间 - 提前生成天数"自动计算，时间可自定义设置-->
<!--          </div>-->
        </el-form-item>
        <!-- 动态字段在弹窗中渲染 -->
        <el-col :span="12" v-for="col in columns" :key="col.key">
          <el-form-item :label="col.label" :prop="col.key">
            <el-input v-model="formData[col.key]" :placeholder="`请输入${col.label}`" style="width: 400px"/>
          </el-form-item>
        </el-col>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 动态添加列的对话框 -->
    <el-dialog v-model="showAddColumnDialog" title="管理列信息">
      <el-button :icon="Plus" @click="showAddColumnDialog2 = true; columnDialogTitle = '新建'" type="primary"
                 style="margin-bottom: 20px;">新建列
      </el-button>
      <el-table :data="columns">
        <el-table-column prop="label" label="列名称" align="center"/>
        <el-table-column prop="key" label="列编码" align="center"/>
        <el-table-column prop="visible" label="是否展示" align="center">
          <template #default="scope">
            {{ scope.row.visible ? "是" : '否' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button @click="editColumn(scope.row, scope.$index)" size="small" icon="Edit">编辑</el-button>
            <el-button @click="deleteColumn(scope.$index)" size="small" type="danger" icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="showAddColumnDialog = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 动态添加列的对话框 -->
    <el-dialog v-model="showAddColumnDialog2" :title="columnDialogTitle">
      <el-form>
        <el-form-item label="列名称">
          <el-input v-model="newColumn.label" placeholder="请输入列名称"/>
        </el-form-item>
        <el-form-item label="列Key">
          <el-input v-model="newColumn.key" placeholder="请输入列Key"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddColumnDialog2 = false">取消</el-button>
        <el-button type="primary" @click="addColumn">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import SearchForm from '@/components/SearchForm.vue';
import {useMaterialata} from '@/hooks/device/cycleManagement';
import {Delete, Edit, Plus} from '@element-plus/icons-vue';
import {ElMessageBox} from 'element-plus';
import {onMounted, computed, ref, watch} from 'vue';
import dayjs from 'dayjs';

const {
  searchParam,
  paginationParams,
  pageTotal,
  paginatedData,
  searchFields,
  handleSearch,
  handleSizeChange,
  handleCurrentChange,
  addmateriaL,
  deletemateriaL,
  isLoading,
  ruleFormRef,
  rules,
  formData,
  week,
  restForm,
  moldType,
  fetchPageData
} = useMaterialata();

// 动态列和新列的数据
const columns = ref([
  // 可添加更多默认列
]);
const showAddColumnDialog = ref(false);
const showAddColumnDialog2 = ref(false);
const columnDialogTitle = ref("")
const columnIndexNumber = ref(0)
const newColumn = ref({
  label: '',
  key: '',
  visible: true,
});

// 修改这里：使用计算属性来处理日期范围
const cycleDateRange = computed({
  get: () => {
    if (formData.value.cycleStartDate && formData.value.cycleEndDate) {
      return [formData.value.cycleStartDate, formData.value.cycleEndDate];
    }
    return [];
  },
  set: (value) => {
    if (value && value.length === 2) {
      formData.value.cycleStartDate = value[0];
      formData.value.cycleEndDate = value[1];
    } else {
      formData.value.cycleStartDate = '';
      formData.value.cycleEndDate = '';
    }
  }
});

// 单独的日期部分（仅年月日，动态计算）
const triggerDateOnly = ref('');
// 单独的时间部分（仅时分秒）
const triggerTimeOnly = ref('');

// 周期有效期变化时触发
const handleCycleDateChange = () => {
  if (formData.value.cycleStartDate && formData.value.advanceDate !== undefined) {
    calculateTriggerTime();
  }
};

// 计算执行开始时刻（周期有效期开始时间 - 提前生成天数）
const calculateTriggerTime = () => {
  if (formData.value.cycleStartDate && formData.value.advanceDate !== undefined) {
    const startDate = dayjs(formData.value.cycleStartDate);
    const triggerDate = startDate.subtract(formData.value.advanceDate, 'day');

    // 更新显示的日期部分
    triggerDateOnly.value = triggerDate.format('YYYY-MM-DD');

    // 如果有设置过时间部分，则更新完整时间
    if (triggerTimeOnly.value) {
      updateFullTriggerTime();
    }
  }
};

// 更新完整的触发时间（当时间部分变化时）
const updateFullTriggerTime = () => {
  if (triggerDateOnly.value && triggerTimeOnly.value) {
    const [hours, minutes, seconds] = triggerTimeOnly.value.split(':');
    const fullTriggerTime = dayjs(triggerDateOnly.value)
        .hour(parseInt(hours))
        .minute(parseInt(minutes))
        .second(parseInt(seconds))
        .format('YYYY-MM-DD HH:mm:ss');

    formData.value.triggerTime = fullTriggerTime;
  }
};

// 初始化 triggerTimeOnly 和 triggerDateOnly
watch(() => formData.value.triggerTime, (newVal) => {
  if (newVal) {
    const date = dayjs(newVal);
    triggerDateOnly.value = date.format('YYYY-MM-DD');
    triggerTimeOnly.value = date.format('HH:mm:ss');
  } else {
    triggerDateOnly.value = '';
    triggerTimeOnly.value = '00:00:00';
  }
}, { immediate: true });

// 当周期开始日期或提前天数变化时，重新计算日期部分
watch([
  () => formData.value.cycleStartDate,
  () => formData.value.advanceDate
], () => {
  if (formData.value.cycleStartDate && formData.value.advanceDate !== undefined) {
    calculateTriggerTime();
  }
});

onMounted(() => {
  moldType.value = 1
  fetchPageData({...searchParam.value, type: 1})
});

// 新建列
const addColumn = () => {
  if (newColumn.value.label && newColumn.value.key) {
    if (columnDialogTitle.value === "新建") {
      columns.value.push({...newColumn.value});
      newColumn.value = {label: '', key: '', visible: true};
      showAddColumnDialog2.value = false
    } else {
      columns.value[columnIndexNumber.value].key = newColumn.value.key
      columns.value[columnIndexNumber.value].label = newColumn.value.label
      columns.value[columnIndexNumber.value].visible = newColumn.value.visible
      showAddColumnDialog2.value = false
    }
  }
};

// 编辑列
const editColumn = (row: any, index: number) => {
  columnIndexNumber.value = index
  columnDialogTitle.value = "编辑"
  showAddColumnDialog2.value = true
  newColumn.value.label = row.label
  newColumn.value.key = row.key
};

// 删除列
const deleteColumn = (index: number) => {
  columns.value.splice(index, 1);
};

const isEdit = ref(false);
const showCrud = ref(false);
const crudTitle = computed(() => {
  return isEdit.value ? '编辑' : '新建';
});

// 新建记录
const handleAdd = () => {
  isEdit.value = false;
  formData.value = {
    ...restForm.value,
    type: 1,
    cycleStartDate: '',
    cycleEndDate: '',
    triggerTime: '' // 重置触发时间
  };
  triggerTimeOnly.value = '00:00:00';
  triggerDateOnly.value = '';
  showCrud.value = true;
};

// 编辑记录
const handleEdit = (row: any) => {
  isEdit.value = true;
  formData.value = {
    ...row,
    type: 1,
    invokeBegin: JSON.parse(row.invokeBegin),
  };
  // 初始化时间部分
  if (formData.value.triggerTime) {
    const date = dayjs(formData.value.triggerTime);
    triggerDateOnly.value = date.format('YYYY-MM-DD');
    triggerTimeOnly.value = date.format('HH:mm:ss');
  }
  showCrud.value = true;
};

// 删除记录
const handleDel = (row: any) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deletemateriaL(row.id);
  }).catch(() => {
  });
};

// 保存记录
const handleSave = async () => {
  await addmateriaL(formData.value, (() => {
    showCrud.value = false;
  }));
};

watch(() => formData.value.triggerCycleType, (newVal) => {
  if (!isEdit.value) {
    switch (newVal) {
      case 1:
        formData.value.invokeFrequency = 0;
        formData.value.advanceDate = 0;
        formData.value.triggerTime = '';
        break;
      case 2:
        formData.value.invokeFrequency = 0;
        formData.value.advanceDate = 0;
        formData.value.invokeBegin = [];
        formData.value.triggerTime = '';
        break;
      case 3:
        formData.value.invokeFrequency = 0;
        formData.value.advanceDate = 0;
        formData.value.invokeBegin = [];
        formData.value.triggerTime = '';
        break;
      default:
        break;
    }
  }
});
</script>

<style scoped>
.trigger-time-container {
  display: flex;
  align-items: center;
}

.trigger-time-hint {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>